package admin

import (
	"SlowAdmin/controllers"
	"SlowAdmin/models"
	"encoding/json"
)

// AdminController 管理员控制器
type AdminController struct {
	controllers.BaseController
}

var adminUserModel = models.AdminUser{}

// @title 添加
func (c *AdminController) Store() {
	var data struct {
		Roles []int `json:"roles"`
	}
	json.Unmarshal(c.Ctx.Input.RequestBody, &data)
	json.Unmarshal(c.Ctx.Input.RequestBody, &adminUserModel)

	var roles []models.AdminRole
	for _, item := range data.Roles {
		var temp models.AdminRole
		temp.Id = uint(item)
		roles = append(roles, temp)
	}
	adminUserModel.Roles = roles

	err := adminUserModel.Store()

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	c.Success("添加成功", nil)
}

// @title 获取列表
func (c *AdminController) List() {
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 15)

	list, total := adminUserModel.GetList(page, pageSize)

	c.Success("ok", controllers.Result{
		"list":      list,
		"total":     total,
		"page":      page,
		"page_size": pageSize,
	})
}

// @title 详情
func (c *AdminController) Find() {
	id := c.Ctx.Input.Param(":id")
	if id == "" {
		c.Fail("参数错误", nil)
		return
	}

	data := adminUserModel.GetOne(id)

	c.Success("ok", data)
}

// @title 更新
func (c *AdminController) Update() {
	var data struct {
		Roles []int `json:"roles"`
	}
	json.Unmarshal(c.Ctx.Input.RequestBody, &data)
	json.Unmarshal(c.Ctx.Input.RequestBody, &adminUserModel)

	var roles []models.AdminRole
	for _, item := range data.Roles {
		var temp models.AdminRole
		temp.Id = uint(item)
		roles = append(roles, temp)
	}
	adminUserModel.Roles = roles

	err := adminUserModel.Update()

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	c.Success("更新成功", nil)
}

// @title 删除
func (c *AdminController) Delete() {
	var data map[string]string
	json.Unmarshal(c.Ctx.Input.RequestBody, &data)

	err := adminUserModel.Delete(data["ids"])

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	c.Success("删除成功", nil)
}

// @title 获取角色列表
func (c *AdminController) RoleList() {
	c.Success("ok", adminRoleModel.GetOptions())
}
